﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Autofac;
using Autofac.Core;
using Domain.Entity.Entities;
using Infrastructure.UnitWork;
using SqlSugar;

namespace Infrastructure
{
    public class InfrastructureAutofacRegister : Autofac.Module
    {
        string connectionString;
        public InfrastructureAutofacRegister(string connectionString)
        {
            this.connectionString = connectionString;
        }
        override protected void Load(ContainerBuilder builder)
        {
            RegisterSqlSugar(builder);

            var repositories = Assembly.GetExecutingAssembly()
                 .GetTypes()
                 .Where(t => t.IsClass && !t.IsGenericType && !t.IsAbstract && t.Name.EndsWith("Repository"));
            builder.RegisterTypes([.. repositories])
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();

            builder.RegisterType<UnitOfWork>()
                   .AsImplementedInterfaces()
                   .InstancePerLifetimeScope();
        }

        private void RegisterSqlSugar(ContainerBuilder builder)
        {
            SqlSugarScope sqlSugar = new(new ConnectionConfig()
            {
                DbType = DbType.MySql,
                ConnectionString = connectionString,
                IsAutoCloseConnection = true,
            }, db =>
            {
                //每次上下文都会执行

                //获取IOC对象不要求在一个上下文
                //var log=s.GetService<Log>()

                //获取IOC对象要求在一个上下文
                //var appServive = s.GetService<IHttpContextAccessor>();
                //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();

                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);
                };
            });
            sqlSugar.DbMaintenance.CreateDatabase();
            sqlSugar.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(User));//根据types创建表
            sqlSugar.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(Order));//根据types创建表

            builder.RegisterInstance(sqlSugar).As<ISqlSugarClient>().SingleInstance();
        }
    }
}
